在java 8中,您可以使用arrays.stream或Stream.of将 Arrays
Array into a Stream.
1. Object Arrays
For object arrays, both Arrays.stream
and Stream.of
returns the same output.
TestJava8.java
package com.mkyong.java8;
import java.util.Arrays;
import java.util.stream.Stream;
public class TestJava8 {
public static void main(String[] args) {
String[] array = {"a", "b", "c", "d", "e"};
//Arrays.stream
Stream<String> stream1 = Arrays.stream(array);
stream1.forEach(x -> System.out.println(x));
//Stream.of
Stream<String> stream2 = Stream.of(array);
stream2.forEach(x -> System.out.println(x));
}
}
Output
a b c d e a b c d e
检查JDK源代码.
Arrays.java
/**
* Returns a sequential {@link Stream} with the specified array as its
* source.
*
* @param <T> The type of the array elements
* @param array The array, assumed to be unmodified during use
* @return a {@code Stream} for the array
* @since 1.8
*/
public static <T> Stream<T> stream(T[] array) {
return stream(array, 0, array.length);
}
Stream.java
/**
* Returns a sequential ordered stream whose elements are the specified values.
*
* @param <T> the type of stream elements
* @param values the elements of the new stream
* @return the new stream
*/
@SafeVarargs
@SuppressWarnings("varargs") // Creating a stream from an array is safe
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
注
对象数组的stream.of方法调用arrays.stream内部。
对象数组的stream.of方法调用arrays.stream内部。